import os
import git
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
from matplotlib import font_manager
import sys


# 配置中文字体
def setup_chinese_font():
    try:
        # 尝试多种常见中文字体路径
        font_paths = [
            "C:/Windows/Fonts/simhei.ttf",  # Windows 黑体
            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",  # Linux 文泉驿
            "/System/Library/Fonts/STHeiti Medium.ttc",  # MacOS
            "C:/Windows/Fonts/msyh.ttf"  # Windows 微软雅黑
        ]

        for path in font_paths:
            if os.path.exists(path):
                font_prop = font_manager.FontProperties(fname=path)
                plt.rcParams['font.sans-serif'] = [font_prop.get_name()]
                plt.rcParams['axes.unicode_minus'] = False
                return font_prop

        # 如果找不到字体，使用系统默认字体
        print("警告: 未找到中文字体，将使用系统默认字体")
        return None

    except Exception as e:
        print(f"字体设置失败: {e}, 将使用默认字体")
        return None


font_prop = setup_chinese_font()

# 配置部分
REPOS = {
    'he3pg': 'https://gitee.com/he3db/he3pg.git',
    'PandaX': 'https://gitee.com/XM-GO/PandaX.git'
}
WORK_DIR = 'repos'
VISUALS_DIR = 'visuals_comparison'
os.makedirs(WORK_DIR, exist_ok=True)
os.makedirs(VISUALS_DIR, exist_ok=True)


def clone_or_update_repo(repo_name, repo_url):
    """克隆或更新Git仓库"""
    repo_path = os.path.join(WORK_DIR, repo_name)
    if os.path.exists(repo_path):
        print(f"正在更新仓库: {repo_name}")
        repo = git.Repo(repo_path)
        repo.remotes.origin.pull()
    else:
        print(f"正在克隆仓库: {repo_name}")
        repo = git.Repo.clone_from(repo_url, repo_path)
    return repo


def get_commit_history(repo):
    """获取仓库的提交历史"""
    commits = list(repo.iter_commits('--all'))
    commit_data = []

    for commit in commits:
        commit_date = datetime.fromtimestamp(commit.committed_date)
        commit_data.append({
            'hash': commit.hexsha,
            'date': commit_date,
            'author': commit.author.name,
            'message': commit.message.strip()
        })

    return pd.DataFrame(commit_data)


def analyze_commits():
    """分析所有仓库的提交历史"""
    all_data = {}

    for repo_name, repo_url in REPOS.items():
        print(f"\n正在处理仓库: {repo_name}")
        repo = clone_or_update_repo(repo_name, repo_url)
        df = get_commit_history(repo)
        df = df.sort_values('date')

        df['cumulative_commits'] = range(1, len(df) + 1)
        daily_commits = df.groupby(df['date'].dt.date).size().reset_index(name='daily_commits')
        daily_commits['date'] = pd.to_datetime(daily_commits['date'])
        daily_commits['cumulative_commits'] = daily_commits['daily_commits'].cumsum()

        all_data[repo_name] = {
            'raw': df,
            'daily': daily_commits,
            'total_commits': len(df)
        }

    return all_data


def save_plot(filename):
    """保存图表到文件"""
    os.makedirs(VISUALS_DIR, exist_ok=True)
    filepath = os.path.join(VISUALS_DIR, filename)
    plt.savefig(filepath, dpi=300, bbox_inches='tight')
    plt.close()
    return f"./{VISUALS_DIR}/{filename}"


def generate_md_content(data):
    """生成Markdown内容"""
    md_content = "# 仓库提交分析报告\n\n"

    # 1. 累计提交增长图
    plt.figure(figsize=(12, 6))
    min_date = min([df['daily']['date'].min() for df in data.values()])
    max_date = max([df['daily']['date'].max() for df in data.values()])
    date_range = pd.date_range(start=min_date, end=max_date, freq='D')
    base_df = pd.DataFrame({'date': date_range})

    for repo_name, repo_data in data.items():
        merged = pd.merge(base_df, repo_data['daily'], on='date', how='left')
        merged['cumulative_commits'] = merged['cumulative_commits'].ffill().fillna(0)
        plt.plot(merged['date'], merged['cumulative_commits'],
                 label=f'{repo_name} (总计: {repo_data["total_commits"]})',
                 linewidth=2)

    plt.title('累计提交增长趋势', fontproperties=font_prop)
    plt.xlabel('日期', fontproperties=font_prop)
    plt.ylabel('累计提交数', fontproperties=font_prop)
    plt.legend(prop=font_prop)
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.xticks(rotation=45)
    plt.tight_layout()

    cumulative_path = save_plot('cumulative_commits.png')
    md_content += "## 累计提交对比\n\n"
    md_content += "![累计提交增长图](./visuals_comparison/cumulative_commits.png)\n\n"

    # 2. 提交总数对比图
    plt.figure(figsize=(8, 6))
    repo_names = list(data.keys())
    totals = [df['total_commits'] for df in data.values()]
    bars = plt.bar(repo_names, totals, color=['#1f77b4', '#ff7f0e'])

    plt.title('提交总数对比', fontproperties=font_prop)
    plt.xlabel('仓库名称', fontproperties=font_prop)
    plt.ylabel('提交总数', fontproperties=font_prop)

    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{int(height)}',
                 ha='center', va='bottom', fontproperties=font_prop)

    plt.grid(True, axis='y', linestyle='--', alpha=0.7)
    plt.tight_layout()

    total_path = save_plot('total_commits.png')
    md_content += "## 提交总数对比\n\n"
    md_content += "![提交总数对比图](./visuals_comparison/total_commits.png)\n\n"

    # 3. 详细分析
    md_content += "## 详细分析\n\n"

    for repo_name, repo_data in data.items():
        md_content += f"### {repo_name} 仓库\n\n"
        md_content += f"- **总提交数**: {repo_data['total_commits']}\n"

        first_commit = repo_data['raw']['date'].min()
        last_commit = repo_data['raw']['date'].max()
        md_content += f"- **首次提交**: {first_commit.strftime('%Y-%m-%d')}\n"
        md_content += f"- **最后提交**: {last_commit.strftime('%Y-%m-%d')}\n"

        active_days = (last_commit - first_commit).days + 1
        commits_per_day = repo_data['total_commits'] / active_days
        md_content += f"- **活跃天数**: {active_days}\n"
        md_content += f"- **日均提交数**: {commits_per_day:.2f}\n\n"

        # 作者统计
        md_content += "#### 作者贡献统计\n\n"
        if 'author' in repo_data['raw'].columns:
            author_stats = repo_data['raw']['author'].value_counts()
            md_content += "| 作者 | 提交数 |\n"
            md_content += "|------|-------|\n"
            for author, count in author_stats.items():
                md_content += f"| {author} | {count} |\n"
            md_content += "\n"
        else:
            md_content += "未找到作者贡献数据。\n"

    return md_content


def main():
    # 设置标准输出编码为UTF-8
    if sys.stdout.encoding != 'UTF-8':
        try:
            import io
            sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
        except AttributeError:
            pass  # 在不支持的环境下跳过

    # 分析提交数据
    commit_data = analyze_commits()

    # 生成Markdown内容
    md_content = generate_md_content(commit_data)

    # 写入Markdown文件(使用UTF-8编码)
    with open('comparison_report.md', 'w', encoding='utf-8') as f:
        f.write(md_content)

    print("\n分析完成! 结果已保存到 comparison_report.md")
    print(f"所有可视化图片已保存到 {VISUALS_DIR} 目录")


if __name__ == '__main__':
    main()